﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WebApiFrameworkJWTDemo.Common
{
    /// <summary>
    /// RSA密钥对：公钥和私钥
    /// </summary>
    public struct RSAKey
    {
        public string PublicKey { get; set; }
        public string PrivateKey { get; set; }
    }
    public class RSAUtil
    {
        private const int DWKEYSIZE = 1024;

        #region 获取RSA密钥对
        /// <summary>
        /// 得到RSA密匙对
        /// </summary>
        /// <returns></returns>
        public static RSAKey GetRASKey()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            return new RSAKey()
            {
                PublicKey = rsa.ToXmlString(false),
                PrivateKey = rsa.ToXmlString(true)
            };
        }
        #endregion

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="content">加密前的内容</param>
        /// <returns>加密字符串</returns>
        public static string Encrypt(string content)
        {
            string publickey = File.ReadAllText(HttpContext.Current.Server.MapPath("~/") + "/Content/publicKey.txt");
            return Encrypt(publickey, content);
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publickey">公钥</param>
        /// <param name="content">加密前的内容</param>
        /// <returns>加密字符串</returns>
        public static string Encrypt(string publickey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);

            return Convert.ToBase64String(cipherbytes);
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="content">加密字符串</param>
        /// <returns>加密前的内容</returns>
        public static string Decrypt(string content)
        {
            string privatekey = File.ReadAllText(HttpContext.Current.Server.MapPath("~/") + "/Content/privateKey.txt");
            return Decrypt(privatekey, content);
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="privatekey">私钥</param>
        /// <param name="content">加密字符串</param>
        /// <returns>加密前的内容</returns>
        public static string Decrypt(string privatekey, string content)
        {
            privatekey = File.ReadAllText(HttpContext.Current.Server.MapPath("~/") + "/Content/privateKey.txt");
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);

            return Encoding.UTF8.GetString(cipherbytes);
        }
    }
}
